package tjs.study.mini.spingmvcmini;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import tjs.study.mini.spingmvcmini.config.MyWebAppInitializer;
import tjs.study.mini.spingmvcmini.config.servlet.DispatcherServlet;
import tjs.study.mini.spingmvcmini.config.tomact.SpringServletContainerInitializer;

import javax.servlet.ServletException;
import java.io.File;


public class DoTest {

    /**
     * ******************************* 数据流向 *******************************
     * tomact.Context.start时，会回调【/META-INF/services/javax.servlet.ServletContainerInitializer】下配置的实现类
     * {@link SpringServletContainerInitializer#onStartup(java.util.Set, javax.servlet.ServletContext)}
     * {@link MyWebAppInitializer#onStartup(javax.servlet.ServletContext))}
     * {@link DispatcherServlet#init()}
     * ( webApplicationContext.refresh();// 初始化IOC上下文)
     * ( initStrategies// 初始化mvc)
     */
    public static void main(String[] args) throws ServletException, LifecycleException {
        start();
    }

    public static void start() throws LifecycleException, ServletException {
        //创建tomcat服务器
        Tomcat tomcatServer = new Tomcat();

        //构建Connector对象,此对象负责与客户端的连接.
        Connector con = new Connector("HTTP/1.1");
        //设置服务端的监听端口
        con.setPort(8083);
        //将Connector注册到service中
        tomcatServer.getService().addConnector(con);

        //读取项目路径,'/'可以加载静态资源
        StandardContext ctx = (StandardContext) tomcatServer.addWebapp(
                "/", new File("./").getAbsolutePath()
        );

        //禁止重新载入
        ctx.setReloadable(false);

        SpringServletContainerInitializer starter = new SpringServletContainerInitializer();

        //也可以配置 /META-INF/services/javax.servlet.ServletContainerInitializer文件
        //ctx.addServletContainerInitializer(starter, Collections.singleton(MyWebAppInitializer.class));

        tomcatServer.start();
        System.out.println("Java语言创建Tomcat启动成功");
        //异步进行接收请求
        tomcatServer.getServer().await();
    }
}
